package com.itheima.health.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.health.entity.PageResult;
import com.itheima.health.entity.QueryPageBean;
import com.itheima.health.mapper.SetmealMapper;
import com.itheima.health.pojo.Setmeal;
import com.itheima.health.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 体检套餐服务实现类
 */
@Service
public class SetmealServiceImpl implements SetmealService {

    @Autowired
    private SetmealMapper setmealMapper;

    @Override
    @Transactional
    public void add(Integer[] checkgroupIds, Setmeal setmeal) {
        //1.添加套餐
        setmealMapper.add(setmeal);
        if(checkgroupIds != null && checkgroupIds.length > 0){
            //2.添加套餐和检查组关联关系
            for (Integer checkgroupId : checkgroupIds) {
                setmealMapper.setSetmealAndCheckGroup(setmeal.getId(),checkgroupId);
            }
        }
    }

    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        //1. 设置分页参数
        PageHelper.startPage(queryPageBean.getCurrentPage(),queryPageBean.getPageSize());
        //2. 执行查询
        Page<Setmeal> page = setmealMapper.selectByCondition(queryPageBean.getQueryString());
        //3. 封装到PageResult中并返回
        return new PageResult(page.getTotal(),page.getResult());
    }

    @Override
    public Setmeal findById(Integer id) {
        //1. 根据id查询套餐
        return setmealMapper.findById(id);
    }

    @Override
    public void edit(Integer[] checkgroupIds, Setmeal setmeal) {
        //1.根据传过来的套餐对象编辑套餐
        setmealMapper.edit(setmeal);
        //2.删除套餐和检查组关联关系
        setmealMapper.delet(setmeal.getId());
        //3.重新建立套餐和检查组关联关系
        if(checkgroupIds != null && checkgroupIds.length > 0){
            for (Integer checkgroupId : checkgroupIds) {
                setmealMapper.setSetmealAndCheckGroup(setmeal.getId(),checkgroupId);
            }
        }
    }

    /**
     * 删除套餐
     * @param id
     * @return
     */
    @Override
    public Boolean delete(Integer id) {
        //1.根据套餐id查询关联订单的数量
        long count = setmealMapper.findCountBySetMealId(id);
        //2.如果关联订单数量大于0，抛出异常
        if(count > 0){
            throw new RuntimeException("当前套餐被引用，不能删除");
        }
        //3.删除套餐和检查组关联关系
        setmealMapper.delet(id);
        //4.删除套餐
        int i = setmealMapper.delete(id);
        if(i > 0){
            return true;
        }
        return false;
    }

    @Override
    public List<Setmeal> findAll() {
        return setmealMapper.findAll();
    }
}
